var express = require("express");
var bodyParser = require("body-parser");
const jsdom = require("jsdom");
const {Script} = require("vm");
const virtualConsole = new jsdom.VirtualConsole({omitJSDOMErrors: true});
const cookieJar = new jsdom.CookieJar();
const {JSDOM} = jsdom;
require('events').EventEmitter.defaultMaxListeners = 0;
var api = express();
api.use(bodyParser.urlencoded({
    parameterLimit: 50000,
    limit: '50mb',
    extended: false
}));
api.get('/api/get', function (req, res) {
    res.send('hello');
});
function randomString(len) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';   
    var maxPos = $chars.length;
    var pwd = '';
    for (i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}
api.post('/api/trademark_get_param/post', function (req, res) {
    var ht = req.body.html.toString();
    var cookies = req.body.cookies.toString();
    plugins = [];
    for(var i; i<Math.round(Math.random() * 50); i++){
        plugins.push({'name': randomString(Math.round(Math.random() * 30)) + " plugin"})
    }

    var options = {
        referrer: "",
        userAgent: "Mozilla/6.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko",
        resources: "usable",    // 假如你想通过<script src="">来执行外部脚本，你需要确保已经加载了它们。为此，请添加选项resources:"usable"
        runScripts: "dangerously",
        url: "",
        beforeParse(window) {

            window.screen = {width: 2560, availHeight: 1400, availLeft: 0, availTop:0, availWidth: 2560,colorDepth: 24, height: 1440, pixelDepth: 24, orientation: {
                    angle:0,
                    type: "landscape-primary"
                }};
            window.getjs = () => {
                return window.js
            };
            window.navigator.languages = ["zh-CN", "zh"];
            window.navigator.plugins = plugins
            window.navigator.getBattery = () => {
                return {
                    'charging': true,
                    'chargingTime': 0,
                    'dischargingTime': Infinity,
                    'level': 1,
                }
            };
            window.navigator.mimeTypes = [{"type": "application/360softmgrplugin"}, {"type": "application/aliedit"}, {"type": "application/asx"}, {"type": "application/bd-npyunwebdetect-plugin"}, {"type": "application/cenroll.cenroll.version.1"}, {"type": "application/futuresplash"}, {"type": "application/futuresplash"}, {"type": "application/futuresplash"}, {"type": "application/futuresplash"}, {"type": "application/hwepass2001.installepass2001"}, {"type": "application/hwpta.itrushwpta"}, {"type": "application/hwwdkey.installwdkey"}, {"type": "application/itrusenroll.certenroll.version.1"}, {"type": "application/mozilla-npqihooquicklogin"}, {"type": "application/npalicdo"}, {"type": "application/npalissologin"}, {"type": "application/npqqwebgame"}, {"type": "application/nptxsso"}, {"type": "application/npxf-qqminidl"}, {"type": "application/npxluser_plugin"}, {"type": "application/pdf"}, {"type": "application/pta.itruspta.version.1"}, {"type": "application/qscall-plugin"}]
            window.navigator.connection = {
                'downlink': 10,
                'effectiveType': '4g',
                'rtt': 50,
                'saveData': false
            };
            window.Infinity = Infinity
        },
        // virtualConsole: new jsdom.VirtualConsole(),
        cookieJar: new jsdom.CookieJar(),
        pretendToBeVisual: true,
    };

    function cp(val) {
        if (val) {
            // console.log(val);
        }
    }

    if (cookies != "none") {
        options.cookieJar.setCookie(cookies, 'http://wsjs.saic.gov.cn/', cp);
    }
    const dom = (new JSDOM(ht, options));
    const window = dom.window;
    const s = new Script(`
      window.document.body.click()
    `);
    dom.runVMScript(s);
    cookies = window.document.cookie;
    resp = {
        'cookie': cookies,
    };
    window.close();
    res.send(JSON.stringify(resp));
});

var server = api.listen(5598, function () {
    var host = '0.0.0.0';
    var port = server.address().port;
    console.log("应用实例，访问地址为 http://%s:%s", host, port)
});

